package com.nbsaas.boot.interceptor;

import com.nbsaas.boot.datasource.DynamicDataSource;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.tenant.api.domain.simple.DatabaseSimple;
import com.nbsaas.boot.tenant.ext.apis.DatabaseExtApi;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class DomainInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private DynamicDataSource dataSource;


    @Resource
    private DatabaseExtApi databaseExtApi;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 获取客户端主机名
        String clientHost = request.getRemoteHost();

        // 获取请求的域名
        String serverName = request.getServerName();
        System.out.println("serverName:" + serverName);

        if (!StringUtils.hasText(serverName)) {
            serverName = "saas.nbsaas.com";
        }

        if (StringUtils.hasText(serverName)) {
            DataSource temp = dataSource.getResolvedDataSources().get(serverName);
            if (temp == null) {
                ResponseObject<DatabaseSimple> res = databaseExtApi.selectByDomain(serverName);
                if (res.getCode() == 200) {
                    dataSource.addDataSource(res.getData());
                    temp = dataSource.getResolvedDataSources().get(serverName);
                }
            }
            if (temp == null) {
                throw new RuntimeException("无效应用");
            }
            DynamicDataSource.setDataSourceKey(serverName);

        } else {
            throw new RuntimeException("无效应用");
        }
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        DynamicDataSource.clearDataSourceKey();
    }
}
